﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Scheduler;
using AzureTracer.Resources;

namespace AzureTracer
{
    public class AgentManager
    {
        const string periodicTaskName = "AzurePeriodicAgent";


        public static void StartPeriodic()
        {
            // Obtain a reference to the period task, if one exists
            PeriodicTask periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (periodicTask != null)
                RemoveAgent();

            periodicTask = new PeriodicTask(periodicTaskName);


            periodicTask.Description = labels.Description;
            periodicTask.ExpirationTime = DateTime.Now.AddDays(14);

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(periodicTask);

                //// If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG)
                    ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(60));
#endif
            }
            catch (InvalidOperationException exception)
            {
                //if (exception.Message.Contains("BNS Error: The action is disabled"))
                //{
                //}

                //if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                //{
                //    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.

                //}
            }
            catch (SchedulerServiceException)
            {
                // No user action required
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    // An unhandled exception has occurred; break into the debugger
                    System.Diagnostics.Debugger.Break();
                }
            }
        }

        public static void RemoveAgent()
        {
            try
            {
                ScheduledActionService.Remove(periodicTaskName);
            }
            catch (Exception) { }
        }
    }
}
